/*
 * FileName: ZkUtil.java
 * Author:   zzw
 * Date:     2018年05月26日
 * Description: zookeeper工具类
 */
package com.zzw.utils;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 〈zookeeper工具类〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class ZkUtil {

    /**
     * server列表, 以逗号分割
     */
    protected String hosts = "localhost:4180,localhost:4181,localhost:4182";
    /**
     * 连接的超时时间, 毫秒
     */
    private static final int SESSION_TIMEOUT = 5000;
    private CountDownLatch connectedSignal = new CountDownLatch(1);
    protected ZooKeeper zk;

    /**
     * 连接zookeeper server
     */
    public void connect() throws Exception {
        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new ConnWatcher());
        // 等待连接完成
        connectedSignal.await();
    }

    public class ConnWatcher implements Watcher {

        @Override
        public void process(WatchedEvent event) {
            // 连接建立, 回调process接口时, 其event.getState()为KeeperState.SyncConnected
            if (event.getState() == Event.KeeperState.SyncConnected) {
                // 放开闸门, wait在connect方法上的线程将被唤醒
                connectedSignal.countDown();
            }
        }
    }

    /**
     * 创建临时节点
     */
    public void create(String nodePath, byte[] data) throws Exception {
        zk.create(nodePath, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    }

    /**
     * 创建znode结点
     * @param path 结点路径
     * @param data 结点数据
     * @return true 创建结点成功 false表示结点存在
     * @throws Exception
     */
    public  boolean addZnodeData(String path,String data,CreateMode mode) {
        try {
            if(zk.exists(path, true) == null){
                zk.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, mode);
                return true;
            }
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException("创建znode："+path+"出现问题！！",e);
        }
        System.out.println("znode"+path+"结点已存在");
        return false;
    }

    /**
     * 创建永久znode结点
     * @param path 结点路径
     * @param data 结点数据
     * @return true 创建结点成功 false表示结点存在
     * @throws Exception
     */
    public  boolean addPZnode(String path,String data) {
        return addZnodeData(path,data,CreateMode.PERSISTENT);
    }

    /**
     * 创建临时znode结点
     * @param path 结点路径
     * @param data 结点数据
     * @return true 创建结点成功 false表示结点存在
     * @throws Exception
     */
    public  boolean addZEnode(String path,String data) {
        return addZnodeData(path,data,CreateMode.EPHEMERAL);
    }

    /**
     * 修改znode
     * @param path 结点路径
     * @param data 结点数据
     * @return  修改结点成功   false表示结点不存在
     */
    public  boolean updateZnode(String path,String data){
        try {
            Stat stat=null;
            if((stat = zk.exists(path, true))!=null){
                zk.setData(path, data.getBytes(), stat.getVersion());
                return true;
            }
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException("修改znode："+path+"出现问题！！",e);
        }
        return false;
    }
    /**
     *
     * 删除结点
     * @param path 结点
     * @return true 删除键结点成功  false表示结点不存在
     */
    public  boolean deleteZnode(String path){
        try {
            Stat stat=null;
            if((stat=zk.exists(path, true))!=null){
                List<String> subPaths=zk.getChildren(path, false);
                if(subPaths.isEmpty()){
                    zk.delete(path, stat.getVersion());
                    return true;
                }else{
                    for (String subPath : subPaths) {
                        deleteZnode(path+"/"+subPath);
                    }
                }
            }
        } catch (InterruptedException | KeeperException e) {
            throw new RuntimeException("删除znode："+path+"出现问题！！",e);
        }
        return false;
    }
    /**
     * 取到结点数据
     * @param path 结点路径
     * @return null表示结点不存在 否则返回结点数据
     */
    public  String getZnodeData(String path){
        String data=null;
        try {
            Stat stat=null;
            if((stat=zk.exists(path, true))!=null){
                data=new String(zk.getData(path, true, stat));
            }else{
                System.out.println("znode:"+path+",不存在");
            }
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException("取到znode："+path+"出现问题！！",e);
        }
        return data;
    }
}
